package edu.hawaii.myisern.action;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.MalformedURLException;
import org.junit.Before;
import org.junit.Test;
import org.xml.sax.SAXException;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;

/**
 * Test Class for SanityCheckActionBean.java
 * @author Shaoxuan Zhang
 *
 */
public class TestSanityCheckActionBean {
  /** Get the test host. */
  //private String testHost = "http://localhost:8080/";
  private String testHost = "http://localhost:8080/";
  private WebConversation conversation = new WebConversation();
  private WebRequest sanityCheckRequest;
  private final String HEAD_FRAME = "navigation";
  private final String VIOLATION_TABLE = "violations";

  /**
   * Initialize a web conversation.
   * @throws MalformedURLException java.net.MalformedURLException
   * @throws IOException java.io.IOException
   * @throws SAXException thrown if there is an error parsing this response
   */
  @Before public void setUp() throws MalformedURLException, IOException, SAXException {
    // Get welcome.jsp page and check for successful retrieval
    String Url = testHost + "myisern";
    WebResponse response = conversation.getResponse(Url);
    assertEquals("See if get the right page", "Login", response.getTitle());
    //login
    WebForm form = response.getFormWithID("LoginForm");
    WebRequest request = form.getRequest();
    request.setParameter("username", "admin");
    request.setParameter("password", "admin");
    response = conversation.getResponse(request);
    assertEquals("Check if login succeeded.", 2,response.getFrameNames().length);
    response = response.getSubframeContents(HEAD_FRAME);
    this.sanityCheckRequest = response.getLinkWith("Sanity Check").getRequest();
  }

  /**
   * Test the Collaborations list page.
   * @throws SAXException thrown if there is an error parsing this response
   * @throws IOException java.io.IOException
   */
  @Test public void testListCollaboration() throws SAXException, IOException {
    WebResponse response = this.conversation.getResource(sanityCheckRequest);
    WebTable listTable = response.getTableWithID(VIOLATION_TABLE);
    assertEquals("Checking list page title", "Sanity Check", response.getTitle());
    assertTrue("Table should be something inside", listTable.getRowCount() > 10);
    assertEquals("The table should have 2 column", 2, listTable.getColumnCount());
  }
}
